package net.hserver.watermark.ui;


import cn.hutool.core.exceptions.ExceptionUtil;
import cn.hutool.core.io.FileUtil;
import cn.hutool.core.util.StrUtil;
import net.hserver.watermark.util.WaterMarkUtils;

import javax.swing.*;
import java.awt.*;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class UiClient extends JFrame {
    private final JTextField inputField;
    private final JTextField textField;
    private final JTextField outputField;
    private final  DefaultListModel<String> listModel;
    private final JList<String> logList;
    private final DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
    private final JScrollPane scrollPane;

    public UiClient() {
        // 设置窗口标题
        super("四川凌空-水印工具");
        // 创建输入框和按钮
        JLabel label = new JLabel("水印文字:");
        textField = new JTextField(25);
        JButton inputButton = new JButton("导入文件夹");
        JButton outputButton = new JButton("导出文件夹");
        inputField = new JTextField(25);
        outputField = new JTextField(25);

        JButton addButton = new JButton("开始转换");
        // 创建列表组件及其模型
        listModel = new DefaultListModel<>();
        logList = new JList<>(listModel);
        logList.setCellRenderer(new MultiLineCellRenderer());
        // 设置布局
        setLayout(new BorderLayout());

        JPanel main = new JPanel();
        main.setLayout(new BoxLayout(main, BoxLayout.Y_AXIS));

        //水印文字
        JPanel textPanel = new JPanel();
        textPanel.setLayout(new BoxLayout(textPanel, BoxLayout.X_AXIS));
        textPanel.add(label);
        textPanel.add(textField);
        main.add(textPanel);
        //导入
        JPanel inputPanel = new JPanel();
        inputPanel.setLayout(new BoxLayout(inputPanel, BoxLayout.X_AXIS));
        inputPanel.add(inputButton);
        inputPanel.add(inputField);
        main.add(inputPanel);
        //导出
        JPanel outputPanel = new JPanel();
        outputPanel.setLayout(new BoxLayout(outputPanel, BoxLayout.X_AXIS));
        outputPanel.add(outputButton);
        outputPanel.add(outputField);
        main.add(outputPanel);

        JPanel optPanel = new JPanel(new FlowLayout(FlowLayout.CENTER));
        optPanel.add(addButton);
        main.add(optPanel);


        // 第三行：列表
        scrollPane = new JScrollPane(logList);

        // 添加组件到主界面
        add(main, BorderLayout.NORTH);
        add(scrollPane, BorderLayout.CENTER);

//
//        textField.setText("1a的颠三");
//        inputField.setText("E:\\test\\a");
//        outputField.setText("E:\\test\\b");


        // 添加事件监听器
        addButton.addActionListener(e -> {
            String text = textField.getText();
            if (StrUtil.isBlank(text)) {
                JOptionPane.showMessageDialog(this, "水印文字不能为空");
                return;
            }
            String input = inputField.getText();
            if (StrUtil.isBlank(input)) {
                JOptionPane.showMessageDialog(this, "导入文件夹不能为空");
                return;
            }
            String output = outputField.getText();
            if (StrUtil.isBlank(output)) {
                JOptionPane.showMessageDialog(this, "导出文件夹不能为空");
                return;
            }
            File parentInput = new File(input);
            File parentOut = new File(output);
            Map<String, String> resData = new HashMap<>();
            FileUtil.walkFiles(parentInput, file -> {
                if (file.isFile()) {
                    String absolutePath = file.getAbsolutePath();
                    if (WaterMarkUtils.isOK(absolutePath)) {
                        resData.put(absolutePath, absolutePath.replace(parentInput.getAbsolutePath(), parentOut.getAbsolutePath()));
                    }
                }
            });
            addButton.setEnabled(false);


            new SwingWorker<Void, String>() {
                @Override
                protected Void doInBackground() {

                    try {
                        long start = System.currentTimeMillis();
                        int total = resData.size();
                        publish("开始处理数据，一共:" + total + "个文件");
                        int i = 0;
                        int error = 0;
                        for (String value : resData.keySet()) {
                            i++;
                            publish("正在处理:" + i + "个文件，剩余:" + (total - i) + "个文件," + value);
                            try {
                                long l = System.currentTimeMillis();
                                String s = resData.get(value);
                                ByteArrayOutputStream byteArrayOutputStream = WaterMarkUtils.addWaterMarkCommon(text, value, FileUtil.readBytes(value));
//                    new File(s).getParentFile().mkdirs();
                                FileUtil.writeBytes(byteArrayOutputStream.toByteArray(), s);
                                long l1 = System.currentTimeMillis();
                                publish("耗时：" + ((l1 - l) / 1000.0) + " 秒,处理完成:" + s);
                            } catch (Exception e2) {
                                error++;
                                String message = ExceptionUtil.getMessage(e2);
                                publish("文件处理失败:" + value + "," + message);
                                e2.printStackTrace();
                            }
                        }
                        long end = System.currentTimeMillis();
                        publish("累计耗时：" + ((end - start) / 1000.0) + " 秒,失败文件个数:" + error + ",成功文件个数:" + (total - error) + ",累计处理个数:" + total);
                    } catch (Exception e3) {
                        e3.printStackTrace();
                    }
                    addButton.setEnabled(true);
                    return null;
                }

                @Override
                protected void process(List<String> chunks) {
                    // 处理新数据并更新 JList
                    for (String chunk : chunks) {
                        LocalDateTime now = LocalDateTime.now();
                        String formattedString = now.format(formatter);
                        listModel.addElement(formattedString + " " +chunk);
                    }
                }

                @Override
                protected void done() {
                    // 更新完成后，刷新 UI
                    logList.repaint();
                }
            }.execute();


        });

        inputButton.addActionListener((e) -> {
            JFileChooser folderChooser = new JFileChooser();
            folderChooser.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
            int result = folderChooser.showOpenDialog(this);
            if (result == JFileChooser.APPROVE_OPTION) {
                File selectedFolder = folderChooser.getSelectedFile();
                this.inputField.setText(selectedFolder.getAbsolutePath());
                // 显示选择的文件夹路径
                JOptionPane.showMessageDialog(this, "导入文件夹:" + selectedFolder.getAbsolutePath());
            }
        });

        outputButton.addActionListener((e) -> {
            JFileChooser folderChooser = new JFileChooser();
            folderChooser.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
            int result = folderChooser.showOpenDialog(this);
            if (result == JFileChooser.APPROVE_OPTION) {
                File selectedFolder = folderChooser.getSelectedFile();
                this.outputField.setText(selectedFolder.getAbsolutePath());
                // 显示选择的文件夹路径
                JOptionPane.showMessageDialog(this, "导出文件夹:" + selectedFolder.getAbsolutePath());
            }
        });


        // 设置窗口属性
        setSize(600, 700);
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        setLocationRelativeTo(null); // 将窗口置于屏幕中央
        setVisible(true);
    }

//    public synchronized void addLog(String msg) {
//        if (msg != null && !msg.trim().isEmpty()) {
//            if (listModel.size() > 50000) {
//                listModel.remove(0);
//            }
//            LocalDateTime now = LocalDateTime.now();
//            String formattedString = now.format(formatter);
//            listModel.add(formattedString + " " + msg);
//            logList.setListData(listModel.toArray(new String[0]));
//            try {
//                logList.revalidate();  // 重新验证布局
//                logList.repaint();     // 强制重绘组件
//                JScrollBar verticalScrollBar = scrollPane.getVerticalScrollBar();
//                verticalScrollBar.setValue(verticalScrollBar.getMaximum());
//            }catch (Exception ignored){}
//
//        }

//    }
}
